<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\model\AdmDesignerGlory;
use Doraemon\model\Member;
use Doraemon\tools\ImgUrl;

class GloryController extends Controller
{
    const PAGE_SIZE = 20;
    const GLORY_BASE = 70;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }
    // 列表
    public function index(Request $request,Content $content) {
        if(empty(request()->year)){
            request()->offsetSet('year', date("Y", time()));
        }
        if(empty(request()->month)){
            request()->offsetSet('month', date("m", strtotime("-1 month")));
        }
        $request_data = $request->all();
        $request_data = self::_filterWhere($request_data);

        $and = (array)$request_data['AND'];
        $limitArr = $request_data['LIMIT'];
        $params = [
            'ORDER' => ['id' => 'DESC'],
            'LIMIT' => $limitArr,
        ];
        if($and) {
            $params['AND'] = $and;
        }
        $itemLiist = AdmDesignerGlory::select('*', $params);
        $total = AdmDesignerGlory::count('*', $and);
        $gridModel = new pGridDataModel($itemLiist, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '用户Uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->year('year', '年份');
                        $filter->month('month', '月份');
                    });
                });

                $grid->column("id", 'ID');
                $grid->column("uid", '用户ID');
                $grid->column("nick", '昵称')->display(function () {
                    $userinfo = Member::getUser($this->uid);
                    return $userinfo['nick'];
                });
                $grid->column("year", '年份');
                $grid->column("month", '月份');
                $grid->column("area_code", '地区');
                $grid->column("glory", '荣耀值');
                $grid->column("adm_glory", 'adm荣耀值');
                $grid->column("pm_glory", 'pm荣耀值');
                $grid->column("cur_score", '预估分')->display(function () {
                    return self::GLORY_BASE + $this->glory - $this->adm_glory + $this->pm_glory;
                });
                $grid->column("total", '总分');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                });
            });

        $tab = new Tab();
        $tab->add('荣耀值列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('荣耀值列表')
            ->description(' ')
            ->breadcrumb(['text' => '荣耀值列表']);
    }

    // 编辑
    public function edit(Request $request,Content $content, $id = 0)
    {
        $request = $request->all();
        if($id == 0) {
            return $content
                ->header('设计师荣耀值 - 编辑')
                ->breadcrumb([
                    'text' => '设计师荣耀值',
                    'url' => '/Designer/glory/',
                ])
                ->body(self::editAction($request, $id , True));
        } else {
            return $content
                ->header('设计师荣耀值 - 编辑')
                ->breadcrumb([
                    'text' => '设计师荣耀值',
                    'url' => '/Designer/glory/',
                ])
                ->body(self::editAction($request, $id, False));
        }
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if(!$isCreate) {
            $data = AdmDesignerGlory::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }

        $form->text('uid', '用户ID')->setWidth(4, 2)->required('不能为空')
            ->help("内部测试号必须用142注册，金额输入0即可；用142注册的内部测试号，无需填写回单编号和上传付款凭证");
        $form->select('package_id', '套餐类型')->setWidth(4, 2)->options(AdmDesignerGlory::PACKAGE_DESC);
        $form->select('pay_platform', '支付方式')->setWidth(4, 2)->options(AdmDesignerGlory::PAY_PLATFORM_DESC);
        $form->text('dsn', '荣耀值号')->setWidth(4, 2)->required('不能为空');
        $form->select('pay_status', '支付状态')->setWidth(4, 2)->options(AdmDesignerGlory::PAY_STATUS_DESC);
        $form->text('real_price', '实付金额')->setWidth(4, 2)->required('不能为空');
        $form->text('certificate_number', '付款凭证编号')->setWidth(4, 2);
        $form->imgUpload('certificate_number_pic', '付款凭证图片', true, [
            'imgType' => ImgUrl::APPTYPE_OP,
            'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI,
        ])->setWidth(4, 2);

        $form->action('/admin/DecoCompany/order/save');

        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();

        $dsn_exist = AdmDesignerGlory::getByDsn($request['dsn']);
        if(!isset($request['id']) && $dsn_exist) {
            throw new InputErrorException('荣耀值号已存在', 403, 'dsn');
        }

        $data = [
            'dsn' => $request['dsn'],
            'uid' => $request['uid'],
            'package_id' => $request['package_id'],
            'package_name' => AdmDesignerGlory::PACKAGE_DESC[$request['package_id']],
            'pay_platform' => $request['pay_platform'],
            'pay_status' => $request['pay_status'],
            'certificate_number' => $request['certificate_number'],
            'certificate_number_pic' => $request['certificate_number_pic'] ?: '',
            'real_price' => $request['real_price'],
            'product_price' => $request['real_price'],
        ];

        $now = time();
        if(isset($request['id']) ) {
            $data['update_time'] = $now;
            $id = $request['id'];

            $rs = AdmDesignerGlory::updateOrder($id, $data);
        } else {
            $data['pay_time'] = $now;
            $rs = AdmDesignerGlory::createOrder($data);
        }

        if($rs) {
            if(isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/DecoCompany/order')->with(compact('success'));
        } else {
            if(isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }
            $error = new MessageBag([
                'title' => $title
            ]);
            return back()->with(compact('error'));
        }
    }
    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        unset($params['per_page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }
}
